import * as THREE from 'three'
import { GangTi } from './GangTi';
import { wuTiCaoZuo, wuLiWorker } from '../../wuLi/WuLiWorker.js'

export class JueSe extends GangTi {
	shiJueSe = true
	zaiDiMian = false // 在地面
		
	constructor(banJing = 0.5, gao = 1) {
		
		const geometry = new THREE.CapsuleGeometry( banJing, gao, 4, 8 );
		const material = new THREE.MeshStandardMaterial()
		const mesh = new THREE.Mesh( geometry, material )
		mesh.userData.xingZhuang = '胶囊'
		
		super(undefined, mesh, 7)
		
		this.wuTiLeiXing = '角色'
		
		this.tianJiaJianTingQi('jiaZaiWanCheng', () => {
			this.touYing()
		})
	}
	
	// 动作动画
	dongZuoDongHua(dongZuo) {
		for (let i = 0, l = this.dongHua.length; i < l; i++) {
			let dongHua = this.dongHua[i]
			// 动画混合有问题 暂不解决
			if (dongHua.getClip().name.includes(dongZuo)) {
				dongHua.setEffectiveWeight(1)
			} else {
				dongHua.setEffectiveWeight(0)
			}
		}
	}
	
	// 设置角色
	/**
	 * @param {Object} sheZhiCanShu
	 * @param {Vector3} sheZhiCanShu.xiangDuiSuDu 相对于站立物体的速度
	 */
	sheZhiJueSe(sheZhiCanShu) {
		if (!this.pengZhuangZhuangTai) return
		let caoZuoShuZu = wuTiCaoZuo[this.bianHao]
	
		if (caoZuoShuZu) {
			let sheZhiCaoZuo = caoZuoShuZu.find(caoZuo => caoZuo.mingZi == 'sheZhiWuTi')
			if (sheZhiCaoZuo) {
				let canShu = sheZhiCaoZuo.canShu
				canShu.sheZhiJueSe = true
				canShu.zou = sheZhiCanShu.zou.toArray()
				canShu.tiao = sheZhiCanShu.tiao.toArray()

			} else {
				let caoZuo = {
					mingZi: 'sheZhiWuTi',
					canShu: {
						bianHao: this.bianHao,
						mingZi: this.mingZi,
						sheZhiChe: true,
						zou: sheZhiCanShu.zou.toArray(),
						tiao: sheZhiCanShu.tiao.toArray()
					}
				}
				
				wuTiCaoZuo[this.bianHao].push(caoZuo)
			}
		}
	}

	tongBu(wuTiCanShu) {
		if (!this.tongBuWuLi || wuLiWorker.tingZhiMoNiZhuangTai) return
		
		let { weiZhi, zaiDiMian } = wuTiCanShu

		this.zaiDiMian = zaiDiMian
		// 同步位置
		let xiangLiang = new THREE.Vector3()
		xiangLiang.set(...weiZhi)
		this.moXing.parent.worldToLocal(xiangLiang)
		this.moXing.position.copy(this.moXing.parent.worldToLocal(xiangLiang))
	}
	
	// 站立
	zhanLi() {
		if (!this.zhongLi) return
		// 角色旋转是moXing驱动物理旋转
		let jieGuoFangXiang = this.zhongLi.clone().normalize().negate()
		this.moXing.updateWorldMatrix(true)
		jieGuoFangXiang.transformDirection(this.moXing.matrixWorld.clone().invert())
		let zhuan = new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), jieGuoFangXiang)
		this.moXing.quaternion.multiply(zhuan)
		let xuanZhuan = this.moXing.getWorldQuaternion(new THREE.Quaternion()).normalize()
		this.sheZhiPengZhuangTi({ xuanZhuan })
	}
	
	gengXin(jianGeShi) {
		this.dongHuaBoFangQi?.update(jianGeShi)
		
		this.shouZhongLi()
		this.zhanLi()
		
		this.xiaCiGengXinHou()
		this.xiaCiGengXinHou = () =>{}
	}
}